package com.siha_back.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.siha_back.config.OSSConfig;
import com.siha_back.entity.dto.User;
import com.siha_back.mapper.UserMapper;
import com.siha_back.service.UserService;
import com.siha_back.utils.ThreadLocalUtil;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OSSConfig ossConfig;
    @Override
    public String uploadFile(MultipartFile file) {
        //获取相关配置
        String bucketName=ossConfig.getBucketName();
        String endPoint=ossConfig.getEndpoint();
        String accessKeyId=ossConfig.getAccessKeyId();
        String accessKeySecret=ossConfig.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        //获取原生文件名
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式
        LocalDateTime time=LocalDateTime.now();
        DateTimeFormatter dft=DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //拼装OSS上存储的路径
        /*String folder=dft.format(time);
        String fileName=generateUUID();*/
        Map<String, Object> map = ThreadLocalUtil.get();
        int userId = (int) map.get("id");
        String extension=originalFilename.substring(originalFilename.lastIndexOf("."));
        //在oss上bucket下的文件名
        String uploadFileName="Resume"+"/"+userId+"/"+"Resume"+extension;
        try {
            PutObjectResult result=ossClient.putObject(bucketName,uploadFileName,file.getInputStream());
            //拼装返回路径
            if (result != null) {
                return "https://"+bucketName+"."+endPoint+"/"+uploadFileName;
            }
        } catch (IOException e) {
            // 打印详细的异常信息
            e.printStackTrace();
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }finally {
            //OSS关闭服务
            ossClient.shutdown();
        }
        return null;

    }
   /* private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }*/
    @Override
    public User findByUserName(String email) {
        User u = userMapper.findByUserName(email);
        return u;
    }

    @Override
    public void register(User user) {
        //注册
        userMapper.add(user);
    }
   /* @Value("${file.upload-dir}")
    private String fileUploadDir;
    public String uploadResumeFile(MultipartFile file){
        try{
            byte[] bytes=file.getBytes();
            Path path= Paths.get(fileUploadDir+ File.separator+file.getOriginalFilename());
            Files.write(path,bytes);
            return "success";
        }catch (Exception e){
            e.printStackTrace();
            return "fail"+e.getMessage();
        }

    }*/


//    @Override
//    public void update(User user) {
//        userMapper.update(user);
//    }
//
//    @Override
//    public void updatePwd(String newPwd) {
//        Map<String,Object> map = ThreadLocalUtil.get();
//        Integer id = (Integer) map.get("id");
//        userMapper.updatePwd(newPwd,id);
//    }


}
